using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using LayoutViewer.Models.Helpers;
using System;

namespace LayoutViewer.Views
{
    public partial class DeviceOptions : Window
    {

        public DeviceOptions()
        {
            this.CanResize = false;
            this.ExtendClientAreaToDecorationsHint = true;
            this.ExtendClientAreaTitleBarHeightHint = -1;
            this.ExtendClientAreaChromeHints = Avalonia.Platform.ExtendClientAreaChromeHints.NoChrome;
            this.InitializeComponent();
#if DEBUG
            this.AttachDevTools();
#endif
        }

        private static string RemoteIP = string.Empty;
        private static string AdbPort = string.Empty;


        private void InitializeComponent()
        {
            AvaloniaXamlLoader.Load(this);
            this.FindControl<TextBox>("RemoteIP").Text = RemoteIP;
            this.FindControl<TextBox>("AdbPort").Text = AdbPort;

        }

        private async void DialogResult()
        {
            BaseHelper helper = null;

            var comboBox = this.FindControl<ComboBox>("DeviceMode");
            if (comboBox.SelectedIndex == 0)
            {
                RemoteIP = this.FindControl<TextBox>("RemoteIP").Text.Trim();
                helper = await ATHelper.Create(RemoteIP);

            }
            else if (comboBox.SelectedIndex == 1)
            {
                RemoteIP = this.FindControl<TextBox>("RemoteIP").Text.Trim();
                AdbPort = this.FindControl<TextBox>("AdbPort").Text ?? string.Empty.Trim();
                helper = new AdbHelper(RemoteIP, Convert.ToInt32(AdbPort));
            }
            this.Close(helper);
        }

        private void OnAcceptTapped(object sender, RoutedEventArgs e)
        {
            this.DialogResult();
        }

        private void OnCancelTapped(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void OnDeviceModeChanged(object sender, SelectionChangedEventArgs e)
        {
            var deviceMode = sender as ComboBox;
            var remoteIPRoot = this.FindControl<Grid>("RemoteIPRoot");
            var adbPortRoot = this.FindControl<Grid>("AdbPortRoot");

            if (deviceMode.SelectedIndex != -1)
            {
                remoteIPRoot.IsVisible = true;
            }

            if (deviceMode.SelectedIndex == 1)
            {
                adbPortRoot.IsVisible = true;
            }
            else
            {
                adbPortRoot.IsVisible = false;
            }
        }
    }
}
